﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using STX.Admin.Models.BizProject;
using STX.Domain;
using STX.Service;

namespace STX.Admin.Controllers
{
    public class BizProjectController : BasePages1Controller<BizProject, IndexModel, AddModel, EditModel, QueryModel>
    {
        public BizProjectService BizProjectService { get; set; }
        public BizAreaService BizAreaService { get; set; }

        protected override void OnInit(out Func<BaseService<BizProject>> thisService, out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc, out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => BizProjectService;
            getIndexModelFunc = () => new IndexModel();
            getAddModelFunc = () => new AddModel
            {
                Areas = new SelectList(BizAreaService.FindAll(),"Id","Name")
            };
            getEditModelFunc = id =>
            {
                var model = BizProjectService.FindModelById(id);
                if (model == null)
                {
                    throw new Exception("找不到此数据");
                }
                return new EditModel
                {
                    Id =model.Id,
                    Name = model.Name,
                    Areas = new SelectList(BizAreaService.FindAll(), "Id", "Name",model.AreaId)
                };
            };
        }

        protected override long AddHandler(AddModel addModel)
        {
            var model = new BizProject
            {
                Name = addModel.Name,
                AreaId = addModel.AreaId
            };
            return BizProjectService.Add(model);
        }

        protected override bool EditHandler(EditModel editModel)
        {
            var model = BizProjectService.FindModelById(editModel.Id);
            if (model == null)
            {
                throw new Exception("找不到此数据");
            }
            model.Name = editModel.Name;
            model.AreaId = editModel.AreaId;
            return BizProjectService.Update(model);
        }

        protected override IQueryable<BizProject> QueryHandler(QueryModel queryModel, IQueryable<BizProject> queryable)
        {
            if (!queryModel.Name.IsNullOrEmpty())
                queryable = queryable.Where(o => o.Name.Contains(queryModel.Name));
            return queryable;
        }
    }
}
